﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Web.Security;
using System.Security.Principal;
using System.Security;

using Revis.VClinicNet.Core.Domain.Credentials;
using Revis.VClinicNet.UI.Internal.Mvc.Extensions;
using System.Web;

namespace Revis.VClinicNet.UI.Internal.Mvc.Infrastructure
{
    public interface IBackLink
    {
        string Url { get; }
    }

    public class HistoryBackLink : IBackLink
    {
        private HttpContextBase _context = null;

        public HistoryBackLink(HttpContextBase context)
        {
            _context = context;
        }

        public string Url
        {
            get
            {
                Uri uri = _context.Request.UrlReferrer;
                string resultUrl = uri != null ? uri.LocalPath : null;
                return resultUrl;
            }
        }

    }

    public enum BackLinkType
    {
        StandardForm, ModifyForm
    }

    public class HistoryBackLinked : ActionFilterAttribute
    {
        public BackLinkType Type { get; set; }

        private IBackLink Last { get; set; }

        public HistoryBackLinked()
        {
            Type = BackLinkType.StandardForm;
        }

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (Type == BackLinkType.ModifyForm) {
                HttpSessionStateBase tempData = filterContext.HttpContext.Session;
                Last = tempData.GetInstance<IBackLink>();
            }
        }

        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            base.OnActionExecuted(filterContext);
            switch(Type) {
                case BackLinkType.StandardForm:
                    StandardFormWay(filterContext);
                    break;
                case BackLinkType.ModifyForm:
                    ModifyFormWay(filterContext);
                    break;
            }            
        }

        private void ModifyFormWay(ActionExecutedContext filterContext)
        {
            HttpSessionStateBase tempData = filterContext.HttpContext.Session;
            tempData.AddInstance<IBackLink>(Last);
        }

        private void StandardFormWay(ActionExecutedContext filterContext)
        {
            HttpSessionStateBase tempData = filterContext.HttpContext.Session;
            tempData.AddInstance<IBackLink>(new HistoryBackLink(filterContext.HttpContext));
        }
    }    
}
